﻿using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

namespace JESAI.Common.Util
{
    public class QrCodeUtility
    {
        public static MemoryStream CreateCode(string text, QrCdoeParams codeParams)
        {
            if (String.IsNullOrEmpty(text)) throw new ArgumentNullException("Text Is Null");
            if (codeParams == null) codeParams = new QrCdoeParams();

            MemoryStream stream = new MemoryStream();

            var ecl = codeParams.Level;
            var quietZoneModule = codeParams.QuietZone;
            var moduleSize = codeParams.ModulesSize;
            var encoder = new QrEncoder(ecl);
            Gma.QrCodeNet.Encoding.QrCode qrCode = null;
            if (encoder.TryEncode(text, out qrCode))
            {
                var render = new GraphicsRenderer(new FixedModuleSize(moduleSize, quietZoneModule));
                render.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
            }

            return stream;
        }
        private static Bitmap CombinImage(Bitmap sourceImage, Bitmap destBitmap)
        {
            int height = Convert.ToInt32(sourceImage.Height * 0.15);
            int width = Convert.ToInt32(sourceImage.Width * 0.15);

            destBitmap = KiResizeImage(destBitmap, width, height, 0);

            using (var g = Graphics.FromImage(sourceImage))
            {
                //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高); 
                g.DrawImage(sourceImage, 0, 0, sourceImage.Width, sourceImage.Height);

                //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框  
                g.DrawImage(destBitmap, sourceImage.Width / 2 - destBitmap.Width / 2, sourceImage.Width / 2 - destBitmap.Width / 2, destBitmap.Width, destBitmap.Height);
                GC.Collect();
                return sourceImage;

            }
        }
        /// <summary>
        /// Resize图片
        /// </summary>
        /// <param name="bmp">原始Bitmap</param>
        /// <param name="newW">新的宽度</param>
        /// <param name="newH">新的高度</param>
        /// <param name="Mode">保留着，暂时未用</param>
        /// <returns>处理以后的图片</returns>
        private static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH, int Mode)
        {
            try
            {
                Bitmap b = new Bitmap(newW, newH);
                Graphics g = Graphics.FromImage(b);                // 插值算法的质量
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                // 高质量
                g.SmoothingMode = SmoothingMode.HighQuality; g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose(); return b;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// byte[]转换成Image
        /// </summary>
        /// <param name="byteArrayIn">二进制图片流</param>
        /// <returns>Image</returns>
        private static System.Drawing.Image byteArrayToImage(byte[] byteArrayIn)
        {
            if (byteArrayIn == null)
                return null;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArrayIn))
            {
                System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);
                ms.Flush();
                return returnImage;
            }
        }

        public static MemoryStream CreateCodeWidthZLogo(string text, string LogoPatch)
        {
            MemoryStream ms = new MemoryStream();
            Boolean IsFileExits = File.Exists(LogoPatch);
            Bitmap resultImage = null;
            int width = 150; int height = 150;
            byte[] byteList = CreateCode(text, null).ToArray();
            Image imgSource = byteArrayToImage(byteList);
            Bitmap bmpSourceImage = new Bitmap(imgSource, width, height);
            if (IsFileExits)
            {
                Image imgSrc = Image.FromFile(LogoPatch);
                Bitmap bmpAttachImage = new Bitmap(imgSrc);
                resultImage = CombinImage(bmpSourceImage, bmpAttachImage);
            }
            resultImage = bmpSourceImage;
            resultImage.Save(ms, ImageFormat.Jpeg);
            return ms;
        }
    }

    public class QrCdoeParams
    {
        public QrCdoeParams()
        {
            Level = ErrorCorrectionLevel.L;
            QuietZone = QuietZoneModules.Two;
            ModulesSize = 10;
        }

        public ErrorCorrectionLevel Level { get; set; }

        public QuietZoneModules QuietZone { get; set; }

        public int ModulesSize { get; set; }

    }
}
